package com.wondertek.poms.service.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.LocalDateTimeUtils;
import com.wondertek.poms.common.utils.excel.ExportExcel;
import com.wondertek.poms.common.utils.excel.ImportExcel;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.ISpInfoService;
import com.wondertek.poms.dao.po.SpInfo;
import com.wondertek.poms.dao.pojo.SpInfoExcelPojo;
import com.wondertek.poms.service.vo.SpInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.runtime.options.Option;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author evan0213
 * @description
 */
@Api(value = "SpInfoController", description = "内容整合方 接口")
@RestController
@RequestMapping("sp-info")
public class SpInfoController {

	@Autowired
	private ISpInfoService spInfoService;

	/**
	 * 内容整合方全量，用于下拉框
	 *
	 * @return 全量的内容整合方
	 */
	@ApiOperation(value = "内容整合方 全量", notes = "内容整合方 全量")
	@GetMapping("all")
	@MethodLog(module = "内容整合方列表")
	public ResultBean all() {
		List<SpInfo> list = spInfoService.findAll();
		return ResultBean.ok(list);
	}

	/**
	 * 查询内容整合方列表
	 * @param spInfoVo 查询条件
	 * @param page 页码
	 * @param rows 条目数
	 * @param sidx 排序列
	 * @param sord 排序方式
	 * @return 分页查询结果
	 */
	@ApiOperation(value = "内容整合方 列表", notes = "查询内容整合方列表")
	@GetMapping("/list")
	public ResultBean list(SpInfoVo spInfoVo,
						   @RequestParam(defaultValue = "1") int page,
						   @RequestParam(defaultValue = "20") int rows,
						   @RequestParam(defaultValue = "id") String sidx,
						   @RequestParam(defaultValue = "desc") String sord){
		SpInfo spInfo = new SpInfo();
		BeanUtils.copyProperties(spInfoVo,spInfo);
		Page<SpInfo> pages = spInfoService.findAll(spInfo, page, rows, sidx, sord);
		return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
	}

	/**
	 * 内容整合方 新增
	 * @param spInfoVo 条目信息
	 * @return ok
	 */
	@ApiOperation(value = "内容整合方 新增", notes = "新增容整合方")
	@PostMapping(value = "/add")
	public ResultBean add(@RequestBody SpInfoVo spInfoVo){
		List<String> messageList = ValidateFilter.getFilterMessage(spInfoVo, Constants.VALIDATE_DEFAULT);
		if(!messageList.isEmpty()){
			return ResultBean.error(messageList.toString());
		}
		if(isRepeat(spInfoVo)){
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}
		SpInfo spInfo = new SpInfo();
		BeanUtils.copyProperties(spInfoVo, spInfo);
		spInfoService.save(spInfo);
		return ResultBean.ok();
	}

	/**
	 * 内容整合方 详情
	 * @param id 主键
	 * @return 查询详细信息
	 */
	@ApiOperation(value = "内容整合方 详情", notes = "查询内容整合方详情")
	@ApiImplicitParam(name = "id", required = true, paramType = "query", dataType = "Long")
	@GetMapping(value = "/get")
	public ResultBean get(Long id){
		return ResultBean.ok(spInfoService.get(id));
	}

	/**
	 * 内容整合方 删除
	 * @param ids 删除版权所属cp,主键id拼接字符串,以英文逗号分隔
	 * @return ok
	 */
	@ApiOperation(value = "内容整合方 删除", notes = "删除内容整合方")
	@ApiImplicitParam(name = "ids", required = true, dataType = "String", value = "删除版权所属cp,主键id拼接字符串,以英文逗号分隔")
	@DeleteMapping(value = "/del")
	public ResultBean del(String ids){
		if(StringUtils.isNotBlank(ids)){
			String[] idArray = ids.split(",");
			List<Long> idList = Arrays.stream(idArray).distinct().map(Long::parseLong).collect(Collectors.toList());
			idList.forEach(id -> spInfoService.deleteById(id));
		}
		return ResultBean.ok();
	}

	/**
	 * 内容整合方 编辑
	 * @param spInfoVo 条目信息
	 * @return ok
	 */
	@ApiOperation(value = "内容整合方 编辑", notes = "编辑内容整合方")
	@PutMapping(value = "/edit")
	public ResultBean edit(@RequestBody SpInfoVo spInfoVo){
		List<String> messageList = ValidateFilter.getFilterMessage(spInfoVo, Constants.VALIDATE_DEFAULT);
		if(!messageList.isEmpty()){
			return ResultBean.error(messageList.toString());
		}
		if(isRepeat(spInfoVo)){
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}

		SpInfo spInfo = spInfoService.findById(spInfoVo.getId());

		if(!spInfo.getId().equals(spInfoVo.getId())){
			return ResultBean.error("spid不可编辑");
		}

		BeanUtils.copyProperties(spInfoVo, spInfo);
		spInfoService.save(spInfo);
		return ResultBean.ok();
	}

	/**
	 * 导出内容整合方excel文件
	 * @param spInfoVo 查询条件
	 * @param sidx 排序列
	 * @param sord 排序方式
	 * @param response 请求
	 * @return excel文件
	 */
	@ApiOperation(value = "内容整合方 导出", notes = "导出内容整合方excel文件")
	@PostMapping(value = "/export")
	public ResultBean exportSpInfo(SpInfoVo spInfoVo,
								   @RequestParam(defaultValue = "id") String sidx,
								   @RequestParam(defaultValue = "desc") String sord,
								   HttpServletResponse response){
		ExportExcel exportExcel = new ExportExcel("内容整合方数据导出", SpInfoExcelPojo.class, 1);
		SpInfo spInfo = new SpInfo();
		BeanUtils.copyProperties(spInfoVo,spInfo);
		List<SpInfo> lists = spInfoService.findAll(spInfo,sidx,sord);
		List<SpInfoExcelPojo> pojos = lists.stream().map(spInfo1 -> {
			SpInfoExcelPojo spInfoExcelPojo = new SpInfoExcelPojo();
			BeanUtils.copyProperties(spInfo1,spInfoExcelPojo);
			return spInfoExcelPojo;
		}).collect(Collectors.toList());
		try {
			exportExcel.setDataList(pojos);
			exportExcel.write(response,  "SpInfo" + "cpInfo_"+ LocalDateTimeUtils.localDateFormat(LocalDateTime.now(), "yy-MM-dd HH:mm:ss") + ".xlsx");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
		}
		return ResultBean.ok();
	}

	/**
	 * 导入内容整合方excel文件
	 * @param file 导入文件
	 * @return 导入结果
	 */
	@ApiOperation(value = "内容整合方 导入", notes = "导入内容整合方excel文件")
	@PostMapping(value = "/import")
	public ResultBean importSpInfo(MultipartFile file){
		StringBuffer msg = new StringBuffer("导入数据总数->");
		StringBuffer errMessage = new StringBuffer(".错误原因是->");
		AtomicInteger errNum = new AtomicInteger();// 全局错误数
		List<SpInfoExcelPojo> list = new ArrayList<>();
		try{
			ImportExcel ei = new ImportExcel(file, 1 ,0);
			List<SpInfoExcelPojo> dataList = ei.getDataList(SpInfoExcelPojo.class);
			if (CollectionUtil.isNotEmpty(dataList)){
				msg.append(dataList.size() + ".错误数据数->");
				dataList.forEach(v -> importData(errMessage, errNum, v, list));
			}else {
				return ResultBean.error(MessageCodes.get(MessageCodes.M980205));
			}

			if(CollectionUtil.isNotEmpty(list)){
				for(SpInfoExcelPojo pojo : list){
					SpInfo spInfo = new SpInfo();
					BeanUtils.copyProperties(pojo, spInfo);
					spInfoService.save(spInfo);
				}
			}
			msg.append(errNum);
			msg.append(errMessage);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
		}
		if (errNum.get() > 0) {
			return ResultBean.error(msg.toString().replace("[", "").replace("]", "").replace("[]", "").replace("!", ""));
		}
		return ResultBean.ok();
	}

	private boolean isRepeat(SpInfoVo spInfoVo){
		SpInfo temp = new SpInfo();
		temp.setName(spInfoVo.getName());
		Optional<SpInfo> opt = spInfoService.findOne(Example.of(temp));
		if(opt.isPresent()){
			SpInfo spInfo = opt.get();
			if(spInfoVo.getId() != null && !spInfo.getId().equals(spInfoVo.getId())){
				return true;
			}
			if(spInfoVo.getId() == null){
				return true;
			}
		}
		SpInfo temp1 = new SpInfo();
		temp1.setSpId(spInfoVo.getSpId());
		Optional<SpInfo> opt1 = spInfoService.findOne(Example.of(temp1));
		if(opt1.isPresent()){
			SpInfo spInfo = opt1.get();
			if(spInfoVo.getId() != null && !spInfo.getId().equals(spInfoVo.getId())){
				return true;
			}
			if(spInfoVo.getId() == null){
				return true;
			}
		}
		return false;
	}

	private void importData(StringBuffer errMessage, AtomicInteger errNum,SpInfoExcelPojo pojo,List<SpInfoExcelPojo> list){
		if (pojo != null) {
			Boolean flag = true;
			List<String> messageList = ValidateFilter.getFilterMessage(pojo, Constants.VALIDATE_DEFAULT);
			flag = checkData(errMessage, errNum, pojo, flag, messageList,list);

			if (flag) {
				list.add(pojo);
			}
		}
	}

	public Boolean checkData(StringBuffer errMessage, AtomicInteger errNum, SpInfoExcelPojo pojo, Boolean flag, List<String> messageList, List<SpInfoExcelPojo> list) {
		if (flag && !messageList.isEmpty()) {
			errNum.addAndGet(1);
			flag = false;
			errMessage.append("导入出错：" + messageList.toString() + ".  ");
		}
		if (flag) {//如果已经传入的list里有重复的id或者name 也拒绝
			List<SpInfoExcelPojo> data = list.stream().filter(SpInfoExcelPojo ->
					SpInfoExcelPojo.getSpId().equals(pojo.getSpId()) || SpInfoExcelPojo.getName().equals(pojo.getName()))
					.collect(Collectors.toList());
			if (data.size() > 0) {
				errNum.addAndGet(1);
				flag = false;
				errMessage.append("播控方id：" + pojo.getSpId() + " 播控方名称：" + pojo.getName() + " 导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
				return flag;
			}

			SpInfoVo spInfoVo = new SpInfoVo();
			spInfoVo.setSpId(pojo.getSpId());
			spInfoVo.setName(pojo.getName());

			if (isRepeat(spInfoVo)) {
				errNum.addAndGet(1);
				flag = false;
				errMessage.append("播控方id：" + pojo.getSpId() + " 播控方名称：" + pojo.getName() + " 导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
			}

		}
		return flag;

	}
}
